<?php
class Wxinterface {
	//微信服务号
	private $_appid;
	private $_appsecret;
	private $_expires_in;
	private $_access_token;
	private $_wx_type;
	//js-sdk
	//调用页面的完整URL
	private $_jsapi_url;
	//调用凭证
	private $_jsapi_ticket;
	private $_jsapi_ticket_expires_in;
	private $_jsapi_nonceStr;
	private $_jsapi_signature;
	private $_jsapi_timestamp;

	private $CI;
	private $_redis;
	
	//构造函数，获取Access Token
	public function __construct($config = array())
	{
		//初始化CI对象
		$this->CI = & get_instance();
        $this->CI->config->load('weixin');
        $this->_appid = isset($config['appid'])?$config['appid']:$this->CI->config->item('nldou_fuwu_appid');
        $this->_appsecret= isset($config['appsecret'])?$config['appsecret']:$this->CI->config->item('nldou_fuwu_appsecret');
        $this->_wx_type = isset($config['wxtype'])?$config['wxtype']:$this->CI->config->item('nldou_fuwu_type');

        $this->CI->load->model('redis_model');
        $this->_redis=$this->CI->redis_model->getRedisInstance();

		//从缓存中获取access_token
        $cache_res = $this->_redis->get('wxinterface_access_token_'.$this->_wx_type);
	    //超时重新获取
		if ($cache_res === false){
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_appid."&secret=".$this->_appsecret;
			$res = $this->http_request($url);
			$result = json_decode($res, true);
			
			if(!isset($result['errcode'])){
				$this->_access_token= $result["access_token"];
				$this->_expires_in = $result["expires_in"];
                $this->_redis->set('wxinterface_access_token_'.$this->_wx_type,$this->_access_token);
                $this->_redis->expire('wxinterface_access_token_'.$this->_wx_type,$this->_expires_in-600);
			}else{
				echo "errorcode: ".$result['errcode'].";errormsg: ".$result['errmsg'];exit;
			}			
		}else{
//			$this->_expires_in = $cache_res["expires_in"];
			$this->_access_token = $cache_res;
		}
	}
	
	public function get_jsapi_ticket()
	{
		//从缓存中获取jsapi_ticket
        $cache_res = $this->_redis->get('wxinterface_jsapi_ticket_'.$this->_wx_type);
		//超时重新获取
		if ($cache_res === false){
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$this->_access_token."&type=jsapi";
		    $res = $this->http_request($url);
		    $result = json_decode($res, true);
				
			if($result['errcode']==0){
				$this->_jsapi_ticket= $result["ticket"];
				$this->_jsapi_ticket_expires_in = $result["expires_in"];
                $this->_redis->set('wxinterface_jsapi_ticket_'.$this->_wx_type,$this->_jsapi_ticket);
                $this->_redis->expire('wxinterface_jsapi_ticket_'.$this->_wx_type,$this->_jsapi_ticket_expires_in-600);
			}else{
				echo "errorcode: ".$result['errcode'].";errormsg: ".$result['errmsg'];exit;
			}
		}else{
//			$this->_jsapi_ticket_expires_in = $cache_res["expires_in"];
			$this->_jsapi_ticket= $cache_res;
		}		
	}
	
	public function getJsapiSignature($from_url = NULL)
	{
		$this->get_jsapi_timestamp();
        $this->get_jsapi_noncestr();
        $this->get_jsapi_ticket();
        
        if(!empty($from_url)){
        	$this->_jsapi_url=$from_url;
        }
        
        $Ori = "jsapi_ticket=".$this->_jsapi_ticket."&noncestr=".$this->_jsapi_nonceStr."&timestamp=".$this->_jsapi_timestamp."&url=".$this->_jsapi_url;
        $this->_jsapi_signature= sha1($Ori);
        return $this->_jsapi_signature;
	}
	
	public function get_jsapi_noncestr($length = 32)
	{
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		$str = "";
		for ( $i = 0; $i < $length; $i++ )  {
			$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
		}
		$this->_jsapi_nonceStr=$str;
	}
	
	public function get_jsapi_timestamp()
	{
		$this->_jsapi_timestamp = time();
	}
	
	public function getJsapiNonceStr()
	{
		return $this->_jsapi_nonceStr;
	}
	
	public function getAppid()
	{
		return $this->_appid;
	}
	
	public function getAppsecret()
	{
		return $this->_appsecret;
	}
	
	public function getJsapiTimestamp()
	{
		return $this->_jsapi_timestamp;
	}
	
	public function semantic_search($record)
	{
		$data = urldecode(json_encode($record));
		$url = "https://api.weixin.qq.com/semantic/semproxy/search?access_token=".$this->access_token;
		$res = $this->http_request($url, $data);
		return json_decode($res, true);
	}
	
	//HTTP请求（支持HTTP/HTTPS，支持GET/POST）
	protected function http_request($url, $data = '')
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	
	//日志记录
	private function logger($log_content)
	{
		if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
			sae_set_display_errors(false);
			sae_debug($log_content);
			sae_set_display_errors(true);
		}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
			$max_size = 500000;
			$log_filename = "log.xml";
			if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
			file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
		}
	}

	//获取自定义菜单
	public function get_menu_info()
	{
		$url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->_access_token;
		$res=$this->http_request($url);
		return json_decode($res);
	}
	//设置自定义菜单
	public function set_menu($button)
	{
		$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->_access_token;
		//echo $this->_access_token;exit;
		$res=$this->http_request($url,$button);
		return json_decode($res);
	}
	//查询已在微信注册ibeacon设备列表
	public function wx_device_search($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/search?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//查询微信注册ibeacon设备分组列表
	public function wx_device_group_list($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/getlist?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//查询微信注册ibeacon设备分组详情
	public function wx_device_group_detail($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/getdetail?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//新增微信注册ibeacon设备分组
	public function add_wx_device_group($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/add?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//修改微信注册ibeacon设备分组名
	public function edit_wx_device_group_name($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/update?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//删除修改微信注册ibeacon设备分组
	public function delete_wx_device_group($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/delete?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	////从分组中移除设备
	public function delete_wx_device_from_group($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/deletedevice?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//新增微信注册ibeacon设备到分组
    public function add_wx_device_to_group($data)
    {
    	$url="https://api.weixin.qq.com/shakearound/device/group/adddevice?access_token=".$this->_access_token;
    	$res=$this->http_request($url,$data);
    	return json_decode($res,true);
    }
    //发客服消息
    public function send_custom_msg($data){
        $url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->_access_token;
        $res=$this->http_request($url,$data);
        return json_decode($res,true);
    }
    //上传临时素材
    public function upload_temp_media($mediaurl,$mediatype,$medianame)
    {
        //从缓存中获取mediaid
        $cache_res = $this->_redis->get('wxinterface_mediaid_'.$medianame);
        //超时重新获取
        if ($cache_res === false){
            $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->_access_token;
            $url .= "&type=".$mediatype;
            $data = array("media"=>"@".$mediaurl);
            $res = $this->http_request($url,$data);
            $result = json_decode($res, true);

            if(!isset($result['errcode'])){
                if ($mediatype=='thumb') {
                    $this->_redis->set('wxinterface_mediaid_'.$medianame,$result["thumb_media_id"]);
                    $this->_redis->expire('wxinterface_mediaid_'.$medianame,172800);
                    return $result["thumb_media_id"];
                }
                else {
                    $this->_redis->set('wxinterface_mediaid_'.$medianame,$result["media_id"]);
                    $this->_redis->expire('wxinterface_mediaid_'.$medianame,172800);
                    return $result["media_id"];
                }
            }else{
                log_message('error','微信上传临时素材失败，medianame=，'.$medianame.'mediatype='.$mediatype.
                    '，errcode='.$result['errcode'].'，errmsg='.$result['errmsg']);
                exit;
            }
        }else{
            return $cache_res;
        }
    }

    public function downloadwxfile($url,$dir)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);//对body进行输出
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);

        curl_close($ch);
        $media = array_merge(array('header'=>$httpinfo),array('body' => $package));

        //生成文件名
        preg_match('/\w\/(\w+)/i', $media["header"]["content_type"], $extmatches);
        $fileExt = $extmatches[1];
        $filename = md5(time().uniqid()).".{$fileExt}";

        $fdir = '/home/nldou/webroot/wap'.$dir;
        if(!file_exists($fdir)){
            mkdir($fdir,0777,true);
        }
        file_put_contents($fdir.$filename,$media['body']);
        return  array('dbpath'=>$dir.$filename,'filepath'=>$fdir.$filename);
    }
    public function download_temp_voice($mediaid = array())
    {
        $res = array();
        foreach ($mediaid as $id){
            $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->_access_token."&media_id=".$id;
            $dir = "/upload/files/".date('Ymd',time()).'/';
            $file = $this->downloadwxfile($url,$dir);
            $res[] = $file;
        }
        return $res;
    }
    public function download_temp_image($mediaid = array())
    {
        $res = array();
        foreach ($mediaid as $id){
            $url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->_access_token."&media_id=".$id;
            $dir = "/upload/images/".date('Ymd',time()).'/';
            $image = $this->downloadwxfile($url,$dir);
            $res[] = $image;
        }
        return $res;
    }
    //根据openid获取用户信息
    public function get_user_info($openid)
    {
        $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->_access_token."&openid=".$openid."&lang=zh_CN";
        $res=$this->http_request($url);
        return json_decode($res,true);
    }
    public function get_batch_user_info($data)
    {
        $url="https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=".$this->_access_token;
        $data=json_encode($data);
        $res=$this->http_request($url,$data);
        return json_decode($res,true);
    }
    public function longurl2short($longurl)
    {
        $url="https://api.weixin.qq.com/cgi-bin/shorturl?access_token=".$this->_access_token;
        $data=array("action"=>"long2short","long_url"=>$longurl);
        $data=json_encode($data);
        $res=$this->http_request($url,$data);
        return json_decode($res,true);
    }


}